package com.lc.advertising.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MyLocationStyle;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.lc.advertising.R;
import com.lc.advertising.app.AppActivity;
import com.lc.advertising.base.BaseDialog;
import com.lc.advertising.dialog.MessageDialog;
import com.lc.advertising.gaode.GaodeEntity;
import com.lc.advertising.gaode.OnGaodeLibraryListen;
import com.lc.advertising.http.request.IndexOrderApi;
import com.lc.advertising.http.request.QiangSaveApi;
import com.lc.advertising.http.response.IndexOrderBean;
import com.lc.advertising.http.response.RegisterBean;
import com.lc.advertising.other.IntentKey;
import com.lc.advertising.util.SPUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class MainActivity extends AppActivity implements OnGaodeLibraryListen.DistanceListen, OnGaodeLibraryListen.LocationListen, OnGaodeLibraryListen.DrawTraceListen , LocationSource {

    @BindView(R.id.map_view)
    MapView mapView;
    @BindView(R.id.bottom_tool)
    RelativeLayout bottomTool;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.bottom_sheet)
    RelativeLayout bottomSheet;
    @BindView(R.id.cl_chouti)
    CoordinatorLayout clChouti;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    private BottomSheetBehavior<View> behavior;

    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private LatLng point;
    private Marker marker;
    private AMap aMap;
    List<IndexOrderBean.QiangdanBean> invirstList = new ArrayList<>();
    private BaseQuickAdapter<IndexOrderBean.QiangdanBean, BaseViewHolder> productAdapter;

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    private String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION};
    private GaodeEntity gaodeEntity;
    private MyLocationStyle myLocationStyle;
    private OnLocationChangedListener mListener = null;//定位监听器
    private String longitude;
    private String latitude;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        SPUtil.put(this,"agree","agree");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);


        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        mapView.onCreate(savedInstanceState);
        requestPermission();


        behavior = BottomSheetBehavior.from(bottomSheet);

        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, @BottomSheetBehavior.State int newState) {
                String state = "null";
                switch (newState) {
                    case 1:
                        bottomTool.setVisibility(View.GONE);
                        state = "STATE_DRAGGING";//过渡状态此时用户正在向上或者向下拖动bottom sheet
                        break;
                    case 2:
                        bottomTool.setVisibility(View.GONE);
                        state = "STATE_SETTLING"; // 视图从脱离手指自由滑动到最终停下的这一小段时间

                        break;
                    case 3:
                        bottomTool.setVisibility(View.GONE);
                        state = "STATE_EXPANDED"; //处于完全展开的状态

                        break;
                    case 4:
                        state = "STATE_COLLAPSED"; //默认的折叠状态

                        bottomTool.setVisibility(View.GONE);
                        break;
                    case 5:
                        state = "STATE_HIDDEN"; //下滑动完全隐藏 bottom sheet
                        bottomTool.setVisibility(View.VISIBLE);
                        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                        break;
                }

            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
//                Log.d("BottomSheetDemo", "slideOffset:" + slideOffset);
            }
        });


        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        productAdapter = new BaseQuickAdapter<IndexOrderBean.QiangdanBean, BaseViewHolder>(R.layout.item_product, invirstList) {
            @Override
            protected void convert(@NotNull BaseViewHolder holder, IndexOrderBean.QiangdanBean databean) {
                holder.setText(R.id.tv_dance, databean.getJuli()+"");
                holder.setText(R.id.tv_start, databean.getBegin_place());
                holder.setText(R.id.tv_end, databean.getEnd_place());
                holder.setText(R.id.time, databean.getCreate_time());
              holder.getView(R.id.btn_qiangdan).setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                      new MessageDialog.Builder(getActivity())
                              // 标题可以不用填写
                              .setTitle("立即接单")
                              // 内容必须要填写
                              .setMessage("是否接单")
                              // 确定按钮文本
                              .setConfirm(getString(R.string.common_confirm))
                              // 设置 null 表示不显示取消按钮
                              .setCancel(getString(R.string.common_cancel))
                              // 设置点击按钮后不关闭对话框
                              //.setAutoDismiss(false)
                              .setListener(new MessageDialog.OnListener() {

                                  @Override
                                  public void onConfirm(BaseDialog dialog) {

                                      qiang_save(  databean.getId()+"");
                                  }

                                  @Override
                                  public void onCancel(BaseDialog dialog) {
                                      dialog.dismiss();
                                  }
                              })
                              .show();

                  }
              });
            }
        };
        recyclerview.setAdapter(productAdapter);
        productAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                startActivity(new Intent(MainActivity.this,GrabbingDetailsActivity.class).putExtra("longitude",longitude).putExtra("latitude",latitude).putExtra("id",invirstList.get(position).getId()+""));
            }
        });
    }

    private void qiang_save(String id) {
        EasyHttp.post(this)
                .api(new QiangSaveApi()
                        .setUid(SPUtil.get(this, IntentKey.UID,"")).setJingdu(longitude).setWeidu(latitude).setId(id))
                .request(new HttpCallback<RegisterBean>(this) {

                    @Override
                    public void onSucceed(RegisterBean data) {
                        toast(data.getMessage());
                        if (data.getCode() == 200) {
                            startActivity(new Intent(MainActivity.this,GrabbingDetailsActivity.class).putExtra("longitude",longitude).putExtra("latitude",latitude).putExtra("id",id));
                        }

                    }


                });
    }

    private void index_order(String longitude,String latitude) {
        EasyHttp.post(this)
                .api(new IndexOrderApi()
                        .setJingdu(longitude).setWeidu(latitude).setPage(1).setUid(SPUtil.get(this,IntentKey.UID,"")))
                .request(new HttpCallback<IndexOrderBean>(this) {

                    @Override
                    public void onSucceed(IndexOrderBean data) {
                        invirstList.clear();
                        invirstList.addAll(data.getQiangdan());
                        productAdapter.setNewData(invirstList);
                        productAdapter.notifyDataSetChanged();
                    }


                });
    }



    //权限管理
    private void requestPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(permissions)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) {
                        if (aBoolean) {
                        initGaodeMap();

                    } else   {
                        boolean fineLocationPermissionApproved =
                                ActivityCompat.checkSelfPermission(MainActivity.this,
                                        Manifest.permission.ACCESS_FINE_LOCATION)
                                        == PackageManager.PERMISSION_GRANTED;
                        if (!fineLocationPermissionApproved) {
                            Toast.makeText(MainActivity.this,"请开启定位权限",Toast.LENGTH_LONG).show();
                            return;
                        }
                        boolean backgroundLocationPermissionApproved =
                                ActivityCompat.checkSelfPermission(MainActivity.this,
                                        Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                                        == PackageManager.PERMISSION_GRANTED;

                        if (!backgroundLocationPermissionApproved){
                            // Denied permission without ask never again
                            Toast.makeText(MainActivity.this,"请始终允许定位，否则应用退到后台或手机锁屏后无法记录运动信息",Toast.LENGTH_LONG).show();
                        }
                    }
                    }
                });
    }

    private void initGaodeMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setMyLocationStyle(aMap);
            /**
             * 千万记得在application中初始化UtilsContextOfGaode.init(this);
             */
            gaodeEntity = new GaodeEntity(this);
//            gaodeEntity = new GaodeEntity(this);
            gaodeEntity.setDistanceListen(this);
            gaodeEntity.setLocationListen(this);
            gaodeEntity.setDrawTraceListen(this);
            gaodeEntity.startLocation();
        }
    }
    /**
     * 设置地图参数
     */
    private void setMyLocationStyle(AMap aMap) {

        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();

        //设置定位监听
        aMap.setLocationSource(this);
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(true);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);
        //初始化定位蓝点样式类
        myLocationStyle = new MyLocationStyle();
//         myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE );//连续定位、
        /// 且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。
        /// （1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        //连续定位、蓝点不会移动到地图中心点，地图依照设备方向旋转，并且蓝点会跟随设备移动。
//

        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_car));
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        // 缩放级别（zoom）：地图缩放级别范围为【4-20级】，值越大地图越详细
//        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));





    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtils.show("再按一次退出程序");

            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }




    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();

    }


    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();

    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }



    @OnClick({R.id.img_people_center, R.id.bottom_tool})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_people_center:
                startActivity(PeopleCenterActivity.class);
                break;
            case R.id.bottom_tool:
                if (behavior.getState() == BottomSheetBehavior.STATE_HIDDEN) {

                    behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);

                }


                break;
        }
    }

    @Override
    public void getCurrentGaodeLocation(AMapLocation amapLocation) {
        if (amapLocation.getErrorCode() == 0) {

              ;
            // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
            if (isFirstLoc) {
                //设置缩放级别
                aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                //将地图移动到定位点
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())));
                //点击定位按钮 能够将地图的中心移动到定位点
                mListener.onLocationChanged(amapLocation);

                //获取定位信息
                StringBuffer buffer = new StringBuffer();
                buffer.append(amapLocation.getCountry() + "" + amapLocation.getProvince() + "" + amapLocation.getCity() + "" + amapLocation.getProvince() + "" + amapLocation.getDistrict() + "" + amapLocation.getStreet() + "" + amapLocation.getStreetNum());
                longitude = amapLocation.getLongitude()+"";
                latitude = amapLocation.getLatitude()+"";
                index_order(longitude, latitude);
                isFirstLoc = false;
            }

        }
    }

    @Override
    public void getDistance(double distance) {

    }

    @Override
    public void drawTrace() {

    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }
}